import 'dart:convert';

import 'package:flutter/cupertino.dart';
import 'package:get/get.dart';
import 'package:get/get_connect/http/src/request/request.dart';

import 'api_log.dart';

class ApiClient extends GetConnect {
  @override
  void onInit() {
    super.onInit();
    httpClient.timeout = Duration(seconds: 10);
    var logInterceptor = LogInterceptor(
      request: true,
      requestHeader: true,
      requestBody: true,
      responseHeader: true,
      responseBody: true,
      error: true,
      maxWidth: 90,
      compact: true,
      logPrint: (object) {
        debugPrint(object.toString());
      },
    );

    httpClient.addRequestModifier(logInterceptor.requestInterceptor);
    httpClient.addResponseModifier(logInterceptor.responseInterceptor);
  }

  Future<String?> getRedirectUrl(String url) async {
    var response = await get(url, headers: {
      "Connection": "keep-alive",
      "Accept": "*/*",
      "Content-Type": "application/json",
      "Host": "v.douyin.com",
      "User-Agent": "Apifox/1.0.0 (https://apifox.com)"
    });
    int? statusCode = response.statusCode;

    if (statusCode != null) {
      // 如果服务器返回了重定向，响应的headers中会有Location信息
      var redirectedUrl = response.headers?['location'];
      print('Redirected to $redirectedUrl');
      return redirectedUrl;
    } else {
      // 处理正常的非重定向响应
      return null;
    }
  }
}
